package com.yifeng.shiro.realms;

import java.util.List;

import com.yifeng.po.User;
import com.yifeng.po.Permission;
import com.yifeng.service.IUserService;
import com.yifeng.service.IPermissionService;
import com.yifeng.util.Md5Util;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class CrmRealm extends AuthorizingRealm {

	@Autowired
	private IUserService employeeService;
	
	@Autowired
	private IPermissionService permissionService;
	
	//获取权限信息,以便框架判断资源是否拥有权限
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取当前用户
		User loginUser = (User) principals.getPrimaryPrincipal();
		System.out.println(loginUser);
		//通过当前用户获取用户拥有的权限
		List<Permission> userPermissions =permissionService.findUserPermissionsByLoginUserId(loginUser.getId());
		
		//把用户权限返回shiro框架
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//有一个Permission就要给框架返回一个
		for (Permission permission : userPermissions) {
			if (permission != null) {
				info.addStringPermission(permission.getSn());
			}
		}
		return info;
	}

	
	//获取用户身份信息
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//把token转换为UsernamePasswordToken
		UsernamePasswordToken upt = (UsernamePasswordToken) token;
		//获取用户名
		String username = upt.getUsername();
		//根据用户名获取用户
		User employee = employeeService.findByUsername(username);
		//做逻辑判断
		if (employee == null) {
			throw new UnknownAccountException();
		}
		if (employee.getState() == -1) {
			throw new AuthenticationException("员工已离职！");
		}
		//身份信息返回给框架，让框架做比对
		Object principal = employee;//身份不仅可以是用户名，还可以是整个用户
		Object hashedCredentials = employee.getPassword();//必须保证数据库里面的密码是加密加盐
		ByteSource credentialsSalt = ByteSource.Util.bytes(Md5Util.SALT);
		return new SimpleAuthenticationInfo(principal, hashedCredentials , credentialsSalt , getName());
	}


}
